<!-- 选择票档 -->
<template>
	<div style="background-color: #f04e7c;" v-if="detail !== null">
		<div style="padding: 12px 16px 24px 16px;">
			<div style="font-size: 16px;font-weight: 400;color: white;">{{detail.name}}</div>
			<div style="font-size: 14px;margin-top:10px;color: white;">{{detail.city}} | {{detail.theaterName}}</div>

		</div>

		<div class="cPage">
			<div>
				<div style="font-size: 14px;color:#333333;font-weight: 500;">场次<span
						style="color: #999999;font-weight: 400;margin-left: 15px;">场次时间均为演出当地时间</span></div>
				<div class="rowStart" style="flex-wrap: wrap;">
					<div :class="index == selectTime ? 'cSelectTime' : 'cUnSelectTime' "  @click="onclickTime(index)"
						v-for="(item,index) in detail.sessionTimes" :key="index">{{getTime(item)}}</div>
				</div>

			</div>

			<div style="margin-top: 40px;">
				<div style="font-size: 14px;color:#333333;font-weight: 500;">票档</div>
				<div class="rowStart" style="flex-wrap: wrap; width: 100%;">
					<!-- <div  :class="index == selectMoney ? 'cTickerSelect' : 'cTickerUnselect'" @click="onclickMoney(index)"
						v-for="(item,index) in detail.gradeMoneys" :key="index">{{item}} 元
					</div> -->
					<!-- <div  :class="index == selectMoney ? 'cTickerSelect' : 'cTickerUnselect'" @click="onclickMoney(index)"
						v-for="(item,index) in detail.commissionAmounts" :key="index">{{getGradeAmount(item)}}
					</div> -->
					<div  :class="index == selectMoney ? 'cTickerSelect' : 'cTickerUnselect'" @click="onclickMoney(index)"
						v-for="(item,index) in detail.commissionAmounts" :key="index">
						<div class="colCenter">
							<div class="rowStart" style="font-size: 23rpx;" v-if="checkIsShowGradeName(item)">{{getGradeName(item)}}</div>
							<div class="rowStart">{{getGradePrice(item)}}</div>
						</div>
					</div>
				</div>
			</div>
			
			<!-- 座位图 -->
			<div style="margin-top: 40px; margin-bottom: 60px;" 
			     v-if="detail.seatImg !== undefined && detail.seatImg != null && detail.seatImg.length > 0">
				<div style="font-size: 14px;color:#333333;font-weight: 500;">座位图</div>
				<div class="colCenter marginTop">
					<image style="width: 100%;" :src="detail.seatImg" @click="onPreview(detail.seatImg)"></image>
				</div>
			</div>
		</div>
		
		<div class="cFixBottom rowEnd" style="background-color: #FFFFFF;">
			<div style="flex:1"></div>
			<uni-number-box v-model="tickerNum" style="align-self: center; width: 100px;margin-right: 40px;" :min="1"/>
			<button class="cChooseSite" @click="onPay">去支付</button>
			<uni-pay ref="payRef" :callOpenId="info.custom.openId" successBackType="redirectTo"
					 @success="onPaySuccess" @fail="onPayFail" @cancel="onPayCancel"></uni-pay>
		</div>
		
		<!-- 演唱会类型的购票实名弹框 -->
		<uni-popup ref="concertRef" type="dialog" :maskClick="false">
			<view class="colStart" style="background-color: #FFFFFF; width: 70vw; padding: 30px 30px; border-radius: 20px;">
				<view class="rowCenter" style="font-size: 18px; font-weight: bold; margin-bottom: 20px;">演唱会购票实名信息</view>
				<uni-forms style="margin-top: 20px;" ref="formRef" :value="formData" :rules="rules" err-show-type="toast">
					<uni-forms-item name="userName" required>
						<uni-easyinput :inputBorder="true" :focus="focusUserName" @blur="focusUserName = false"
							class="input-box sxf-easyinput" placeholder="请输入真实姓名" v-model="formData.userName" trim="both" 
							:maxlength="16" />
					</uni-forms-item>
					<uni-forms-item name="phone" required>
						<uni-easyinput :inputBorder="true" :focus="focusPhone" @blur="focusPhone = false"
							class="input-box sxf-easyinput" placeholder="请输入手机号码" v-model="formData.phone" trim="both" 
							:maxlength="11" type="tel"/>
					</uni-forms-item>
					<uni-forms-item name="idCardNumber" required>
						<uni-easyinput :inputBorder="true" :focus="focusIdCardNumber" @blur="focusIdCardNumber = false"
							class="input-box sxf-easyinput" placeholder="请输入身份证号码" v-model="formData.idCardNumber" trim="both" 
							:maxlength="18" type="text"/>
					</uni-forms-item>
					
					<view class="colCenter" style="margin-top: 30px;">
						<view class="rowBetween">
							<button class="marginRight" style="flex: 1;" @click="onCancelConcert">取消</button>
							<button class="marginLeft" style="flex: 3;" type="warn" @click="onSubmitConcert">确定</button>
						</view>
					</view>
				</uni-forms>
			</view>
		</uni-popup>
	</div>
</template>

<script lang="ts" setup>
	import { ref, computed } from "vue"
	import { onReachBottom, onShareAppMessage } from "@dcloudio/uni-app"
	import { onLoad, onShow } from "@dcloudio/uni-app"
	import DbUtil from "@/utils/DbUtil"
	import StrUtil from "@/utils/StrUtils.js"
	import { gzhShare, previewImage } from "@/utils/WxGzhUtil"
	import { useStore } from "vuex"
	
	const sxf_theater = uniCloud.importObject("sxf-theater");
	
	const store = useStore();

	let tickerNum = ref(1)
	let selectTime = ref(0)
	let selectMoney = ref(0)

	let detail = ref(null)
	
	let info = ref({
		provider: "wxpay", // 指定微信支付
		total_fee: 0, // 支付金额，单位分
		order_no: "", // 业务系统订单号
		out_trade_no: "", // 插件支付单号
		description: "sxf订单", // 支付描述
		type: "goods", // 支付回调类型，如：recharge-余额充值，goods-商品订单
		custom: {
			openId: getApp().globalData.curOpenId, // 购票人openid
			userId: getApp().globalData.curUserId, // 购票人userId
			productId: "", // 产品ID
			productName: "", // 产品名称
			coverImg: "", // 产品封面图
			sessionName: "", // 场次名称
			gradeName: "", // 票档名称
			theaterSessionTime:0, // 开演时间
			theaterGradeName: "", // 票档名称
			gradeMoney: 0, // 票档单价（分）
			tickerNum: 0, // 购票数量
			totalMoney: 0, // 购票总价（分）
			recipientName: "", // 取票人名称
			recipientPhone: "", // 取票人电话
			recipientIdCardNumber: "", // 取票人身份证号码（演唱会类型时必填）
			remark: "sxf", // 备注
			shareOpenId: getApp().globalData.shareOpenId, // 分享人openid
			shareUserId: getApp().globalData.shareUserId, // 分享人userId
			channelCommissionAmount: 0, // 配置的渠道佣金金额（分）
			gradeCommissionAmount: 0, // 票档对应的渠道佣金金额（分）
			tickectType: 1, // 票据类型（1-实体票，2-电子票）
		}
	});
	
	let payRef = ref(null);
	
	let userInfo = ref({
		userName: "",
		phone: ""
	});
	
	let formData = ref({
		userName: "",
		phone: "",
		idCardNumber: ""
	});
	
	let formRef = ref(null);
	
	const rules = ref({
		userName: {
			rules: [
				{
					required: true,
					errorMessage: '请输入真实姓名',
				},
				{
					minLength: 2,
					maxLength: 16,
					errorMessage: '姓名长度在 {minLength} 到 {maxLength} 个字符',
				},
				{
					validateFunction: (rule, value, data, callback) => {
						// console.log(value);
						if (/^1\d{10}$/.test(value) || /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/.test(value)) {
							callback('姓名不能是：手机号或邮箱')
						};
						if (/^\d+$/.test(value)) {
							callback('姓名不能为纯数字')
						};
						return true
					}
				}
			],
			label: "真实姓名"
		},
		phone: {
			rules: [
				{
					required: true,
					errorMessage: '请输入手机号码',
				},
				{
					minLength: 11,
					maxLength: 11,
					errorMessage: '手机号码长度是 {minLength} 位数字',
				},
				{
					validateFunction: (rule, value, data, callback) => {
						// console.log(value);
						if (/^1\d{10}$/.test(value)) {
							return true;
						} else {
							callback('手机号码格式不正确');
						}
					}
				}
			],
			label: "手机号码"
		},
		idCardNumber: {
			rules: [
				{
					required: true,
					errorMessage: '请输入身份证号码',
				},
				{
					minLength: 18,
					maxLength: 18,
					errorMessage: '身份证号码长度是 {minLength} 个字符',
				},
				{
					validateFunction: (rule, value, data, callback) => {
						console.log("idCardNumber:", value);
						if (/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$/.test(value)) {
							return true;
						} else {
							callback('身份证号码格式不正确');
						}
					}
				}
			],
			label: "身份证号码"
		},
	});
	
	let focusUserName = ref(false);
	let focusPhone = ref(false);
	let focusIdCardNumber = ref(false);
	
	const concertRef = ref(null);
	
	onLoad(async (options) => {
		detail.value = JSON.parse(decodeURIComponent(options.row))
		console.log(detail, "xxx")
		
		info.value.custom.productId = detail.value.id; // 产品ID
		info.value.custom.productName = detail.value.name; // 产品名称
		info.value.custom.coverImg = detail.value.coverImg; // 产品封面图
		info.value.custom.channelCommissionAmount = detail.value.channelCommissionAmount; // 配置的渠道佣金金额（分）
		info.value.custom.tickectType = detail.value.tickectType; // 票据类型（1-实体票，2-电子票）
		
		gzhShare({
			isShowMenu: false, // 隐藏菜单
			shareInfo: {}
		});
	})
	
	onShow(async (options) => {
		console.log("onShow options:", options);
		
		userInfo.value = store.getters.getUserInfo;
		info.value.custom.openId = getApp().globalData.curOpenId; // 购票人openid
		info.value.custom.userId = getApp().globalData.curUserId; // 购票人userId
		info.value.custom.shareOpenId = getApp().globalData.shareOpenId; // 分享人openid
		info.value.custom.shareUserId = getApp().globalData.shareUserId; // 分享人userId
		
		if (StrUtil.isEmpty(info.value.custom.recipientName)) {
			info.value.custom.recipientName = (!StrUtil.isEmpty(userInfo.value) && !StrUtil.isEmpty(userInfo.value.userName)) ? userInfo.value.userName : ""; // 取票人名称
		}
		if (StrUtil.isEmpty(info.value.custom.recipientPhone)) {
			info.value.custom.recipientPhone = (!StrUtil.isEmpty(userInfo.value) && !StrUtil.isEmpty(userInfo.value.phone)) ? userInfo.value.phone : ""; // 取票人电话
		}
		
		if (StrUtil.isEmpty(formData.value.userName)) {
			formData.value.userName = info.value.custom.recipientName;
		}
		if (StrUtil.isEmpty(formData.value.phone)) {
			formData.value.phone = info.value.custom.recipientPhone;
		}
	})

	const getTime = computed(() => (item : string) => {
		// return item.substring(0, 10).replaceAll('-', '.') + " " + StrUtil.getWeek(item) + item.substring(5, 10).replaceAll('-', '.')
		return getSessionName(item);
	})
	
	const getGradeAmount = computed(() => (item) => {
		if (!StrUtil.isEmpty(item.name)) {
			// return item.name + " " + StrUtil.floatFix(item.grade / 100) + "元"
			let money = StrUtil.floatFix(item.grade / 100) + ''
			if (money.endsWith(".00")) {
				money = money.substring(0, money.length - 3)
			}
			return item.name + " " + money + "元"
		} else {
			return StrUtil.floatFix(item.grade / 100) + "元"
		}
	})
	
	const checkIsShowGradeName = computed(() => (item) => {
		if (!StrUtil.isEmpty(item.name)) {
			return true
		} else {
			return false
		}
	})
	
	const getGradeName = computed(() => (item) => {
		if (!StrUtil.isEmpty(item.name)) {
			return item.name
		} else {
			return ""
		}
	})
	
	const getGradePrice = computed(() => (item) => {
		if (!StrUtil.isEmpty(item.grade)) {
			// return StrUtil.floatFix(item.grade / 100) + "元"
			let money = StrUtil.floatFix(item.grade / 100) + ''
			if (money.endsWith(".00")) {
				money = money.substring(0, money.length - 3)
			}
			return money + "元"
		} else {
			return ""
		}
	})
	
	const onclickTime = (index:number)=>{
		selectTime.value = index
		selectMoney.value = 0
	}
	
	const onclickMoney = (index:number)=>{
		selectMoney.value = index		
	}
	
	// 获取场次名称
	const getSessionName = (sessionTime: string) => {
		if (sessionTime.length == 0 || sessionTime == '下单后时间可以商议') {
			return '下单后时间可以商议';
		}
		return sessionTime.substring(0, 10).replaceAll('-', '.') + " " + StrUtil.getWeek(sessionTime) + " " + sessionTime.substring(11, 16);
	};
	
	// 支付
	const onPay = async () => {
		console.log("onPay----->userInfo.value:", userInfo.value);
		if (StrUtil.isEmpty(userInfo.value) || 
			StrUtil.isEmpty(userInfo.value.phone)) {
			// 未注册用户，先进行注册
			uni.showModal({
				title: "注册提醒",
				content: "您还未注册，现在注册？",
				confirmText: "注册",
				success: (res) => {
					if (res.confirm) {
						uni.navigateTo({
							url: "/pages/launch/regist"
						});
					}
				}
			});
		} else {
			// 已注册用户，可进行购票
			let isHasRecipientInfo = false;
			console.log("categoryName:", detail.value.categoryName);
			if (detail.value.categoryName == "演唱会") {
				// 要实名购票
				if (!StrUtil.isEmpty(info.value.custom.recipientName) && 
				    !StrUtil.isEmpty(info.value.custom.recipientPhone) && 
					!StrUtil.isEmpty(info.value.custom.recipientIdCardNumber)) {
					// 已有实名信息，可购票
					isHasRecipientInfo = true;
				} else {
					// 未有实名信息，弹框录入
					isHasRecipientInfo = false;
					concertRef.value.open();
				}
			} else {
				// 非演唱会，不需要实名
				isHasRecipientInfo = true;
			}
			// console.log("isHasRecipientInfo:", isHasRecipientInfo);
			
			if (isHasRecipientInfo) {
				// 场次名称
				const sessionName = getSessionName(detail.value.sessionTimes[selectTime.value]);
				// 票档金额（元）
				// const gradeMoney = detail.value.gradeMoneys[selectMoney.value];
				// info.value.total_fee = gradeMoney * tickerNum.value * 100; // 订单金额（分）
				info.value.total_fee = detail.value.commissionAmounts[selectMoney.value].grade * tickerNum.value; // 订单金额（分）
				info.value.order_no = "SXF" + Date.now(); // 业务系统订单号（模拟生成订单号）
				info.value.out_trade_no = `${info.value.order_no}-1`; // 插件支付单号
				info.value.description = detail.value.name; // 支付描述
				///
				info.value.custom.theaterSessionTime = new Date(detail.value.sessionTimes[selectTime.value]).getTime()
				info.value.custom.sessionName = sessionName; // 场次名称
				info.value.custom.theaterGradeName = detail.value.commissionAmounts[selectMoney.value].name; // 票档名称
				// info.value.custom.gradeName = `${gradeMoney}元`; // 票档名称
				// info.value.custom.gradeMoney = gradeMoney * 100; // 票档单价（分）
				info.value.custom.gradeName = `${detail.value.commissionAmounts[selectMoney.value].grade / 100}元`; // 票档名称
				info.value.custom.gradeMoney = detail.value.commissionAmounts[selectMoney.value].grade; // 票档单价（分）
				info.value.custom.tickerNum = tickerNum.value; // 购票数量
				info.value.custom.totalMoney = info.value.total_fee; // 购票总价（分）
				info.value.custom.gradeCommissionAmount = detail.value.commissionAmounts[selectMoney.value].amount; // 票档对应的渠道佣金金额（分）
				// info.value.custom.recipientName = userInfo.value.userName ? userInfo.value.userName : ""; // 取票人名称
				// info.value.custom.recipientPhone = userInfo.value.phone ? userInfo.value.phone : ""; // 取票人电话
				///
				// info.value.custom.remark = `场次：${sessionName}, 票档：${gradeMoney}元, 数量：${tickerNum.value}`;
				info.value.custom.remark = `场次：${sessionName}, 票档：${info.value.custom.gradeName}, 数量：${tickerNum.value}`;
				// info.value.custom.tickectType = detail.value.tickectType; // 票据类型（1-实体票，2-电子票）
				// console.log("info====", info);
				if (info.value.total_fee > 0) {
					// 打开支付收银台
					payRef.value.open(info.value);
				} else {
					// 0元免费的，不走微信支付，直接下单
					console.log("info-----", info.value);
					// 直接下单
					const orderRes = await sxf_theater.createProductOrder({ 
						order_no: info.value.order_no, 
						out_trade_no: info.value.out_trade_no, 
						total_fee: info.value.total_fee, 
						custom: info.value.custom 
					});
					// orderRes.code, orderRes.orderId, orderRes.payDate
					
					if (orderRes.code === 0) {
						let url = `/uni_modules/uni-pay/pages/success/success?out_trade_no=${info.value.out_trade_no}&order_no=${info.value.order_no}&pay_date=${orderRes.payDate}&total_fee=${info.value.total_fee}&adpid=&return_url=&main_color=&tickectType=${info.value.custom.tickectType}`;
						uni.redirectTo({
							url,
						});
					} else {
						// 下单失败
						uni.showToast({
							title: "下单失败",
							icon: "fail"
						});
					}
				}
			}
		}
	};
	
	// 支付成功
	const onPaySuccess = () => {
		// 进入支付成功结果页面，不需要重复弹框提示
	};
	
	// 支付失败
	const onPayFail = (err) => {
		uni.showToast({
			title: "支付失败",
			icon: "fail"
		});
	};
	
	// 取消支付
	const onPayCancel = (err) => {
		uni.showToast({
			title: "已取消支付",
			icon: "fail"
		});
	};
	
	// 预览座位图
	const onPreview = (imgUrl) => {
		previewImage(imgUrl, [imgUrl]);
	};
	
	// 取消演唱会实名信息填写
	const onCancelConcert = () => {
		concertRef.value.close();
	};
	
	// 确定演唱会实名信息填写
	const onSubmitConcert = () => {
		formRef.value.validate().then(async (res) => {
			// console.log("----->res:", res);
			// 填充取票人信息
			info.value.custom.recipientName = formData.value.userName; // 取票人名称
			info.value.custom.recipientPhone = formData.value.phone; // 取票人电话
			info.value.custom.recipientIdCardNumber = formData.value.idCardNumber; // 取票人身份证号
			concertRef.value.close();
			// 去支付
			onPay();
		}).catch((errors) => {
			// console.log("----->errors:", errors);
			let key = errors[0].key;
			key = "focus" + key.replace(key[0], key[0].toUpperCase());
			console.log("key:", key);
			if (key === "focusUserName") {
				focusUserName.value = true;
			} else if (key === "focusPhone") {
				focusPhone.value = true;
			} else if (key === "focusIdCardNumber") {
				focusIdCardNumber.value = true;
			}
		});
	};
</script>

<style lang="scss" scoped>
	.cPage {
		border-top-left-radius: 16px;
		border-top-right-radius: 16px;
		background: white;
		padding: 16px;
	}

	.cFixBottom {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 60px;
		border-top: solid 1px #f2f2f2;
	}

	.cSelectTime {
		width: 240px;
		line-height: 48px;
		background-color: white;
		color: #f04e7c;
		font-size: 16px;
		font-weight: 500;
		border: solid 1px #f04e7c;
		border-radius: 6px;
		align-self: center;
		padding-left: 16px;
		margin-top: 16px;
	}
	
	.cUnSelectTime{
		width: 240px;
		line-height: 48px;
		background-color: #f6f6f6;
		color: #555555;
		font-size: 16px;
		font-weight: 500;
		border: solid 1px #999999;
		border-radius: 6px;
		align-self: center;
		padding-left: 16px;
		margin-top: 16px;
	}

	.cTickerSelect {
		// width: 36%;
		background-color: white;
		color: #f04e7c;
		font-size: 16px;
		font-weight: 400;
		border: solid 1px #f04e7c;
		border-radius: 6px;
		align-self: center;
		margin-top: 16px;
		margin-right: 16px;
		padding: 10px 10px;
	}
	
	.cTickerUnselect {
		// width: 36%;
		background-color: #f6f6f6;
		color: #555555;
		font-size: 16px;
		font-weight: 400;
		border: solid 1px #999999;
		border-radius: 6px;
		align-self: center;
		margin-top: 16px;
		margin-right: 16px;
		padding: 10px 10px;
	}
	
	// 小屏
	@media (max-width: 360px) {
		.cTickerSelect {
			width: 36%;
		}
		
		.cTickerUnselect {
			width: 36%;
		}
	}
	
	// 中屏
	@media (min-width: 360px) and (max-width: 428px) {
		.cTickerSelect {
			width: 38%;
		}
		
		.cTickerUnselect {
			width: 38%;
		}
	}
	
	// 大屏
	@media (min-width: 430px) {
		.cTickerSelect {
			width: 40%;
		}
		
		.cTickerUnselect {
			width: 40%;
		}
	}

	.cChooseSite {
		width: 120px;
		line-height: 38px;
		background-color: #f04e7c;
		color: white;
		font-size: 16px;
		font-weight: 500;
		border-radius: 19px;
		align-self: center;
		text-align: center;
		margin-right: 16px;
	}
</style>